package top.roadvast.pdshopping.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.roadvast.pdshopping.bean.PdOrder;
import top.roadvast.pdshopping.service.OrderService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 20:50
 * @Version 1.0
 * @Description rabbitmq监听器
 * 收到订单数据后,会调用订单的业务代码,把订单保存到数据库
 */
@Component
@Slf4j
//添加该注解后,会从队列名为[orderQueue]上接收消息,
@RabbitListener(queues = "order_queue")
public class WorkOrderConsumer {
    @Resource
    OrderService orderService;

    private static int count = 0;

    /**
     * rabbitmq六种工作模式之一：工作模式
     * 模拟：消费者01正常处理，消费者02睡眠2s后处理，
     * 消息手动确认
     *      yaml配置手动确认(spring.rabbitmq.listener.simple.acknowledge-mode: manual)
     *      手动确认：channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
     * 合理分发
     *      yaml配置每次只接收一条消息(spring.rabbitmq.listener.simple.prefetch: 1)
     * 消息持久化
     *      分为队列持久化和消息持久化
     *          队列持久化：config配置类中配置
     *          消息持久化：默认已经持久化了。
     */
    //收到消息后会把数据转为 PdOrder 实例传递到此方法
    @RabbitHandler
    public void save(PdOrder order, Channel channel, Message message) {
        log.info("count = " + (++count));
        try {
            log.info("接收到订单，开始进行处理...");
            log.info("订单信息：" + order);
            orderService.saveOrder(order);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
